package fun.tan90.easy.binlog.manager.handler;

import com.alibaba.fastjson.JSON;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import fun.tan90.easy.binlog.base.constants.EasyBinlogConstants;
import fun.tan90.easy.binlog.base.strategy.AbstractExecuteStrategy;
import fun.tan90.easy.binlog.manager.dataobject.mapper.BinlogMasterMapper;
import fun.tan90.easy.binlog.manager.dataobject.BinlogMaster;
import lombok.extern.slf4j.Slf4j;
import org.noear.socketd.transport.core.Entity;
import org.noear.socketd.transport.core.entity.StringEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static fun.tan90.easy.binlog.manager.dataobject.table.BinlogMasterTableDef.BINLOG_MASTER;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/12/15 19:42
 */
@Slf4j
@Component
public class GetOutputRuleHandler implements AbstractExecuteStrategy<String, Entity> {

    @Resource
    BinlogMasterMapper binlogMasterMapper;

    @Override
    public String mark() {
        return EasyBinlogConstants.GET_OUTPUT_RULE;
    }

    @Override
    public Entity executeResp(String masterCode) {
        BinlogMaster binlogMaster = binlogMasterMapper.selectOneByQuery(
                QueryWrapper
                        .create()
                        .select(BINLOG_MASTER.ID)
                        .where(BINLOG_MASTER.MASTER_CODE.eq(masterCode))
        );
        if (Objects.isNull(binlogMaster)) {
            return new StringEntity("");
        }
        List<Row> rows = Db.selectListBySql(
                "SELECT r.id AS output_rule_count_id, o.output_code, l.schema_regular, l.table_regular, o.output_type FROM binlog_output_rule l LEFT JOIN binlog_output_count r ON r.output_rule_id = l.id LEFT JOIN binlog_output o on r.output_id = o.id " +
                        "WHERE l.master_id = ? AND l.rule_status = ? AND o.output_status = ?", binlogMaster.getId(), "1", "1");
        return new StringEntity(JSON.toJSONString(rows.stream()
                .map(n -> n.getString("output_rule_count_id") + ","
                        + n.getString("output_code") + ","
                        + n.getString("output_type") + ","
                        + n.getString("schema_regular") + ","
                        + n.getString("table_regular"))
                .collect(Collectors.toList())));
    }
}
